package com.zpc.myvideoserver.common.security.service;

import com.zpc.myvideoserver.common.security.pojo.AccountUser;
import com.zpc.myvideoserver.entity.User;
import com.zpc.myvideoserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName : UserDetailServiceImpl  //类名
 * @Description : 用户信息获取实现类  //描述
 * @Author : zpc20 //作者
 * @Date: 2023/11/1  23:22
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * @Name: loadUserByUsername
     * @Params : [username]:[java.lang.String]
     * @Description : 重写loadUserByUsername方法验证用户是否在数据库中
     * @Author : zpc20
     * @Date : 2023/11/2 8:18
     * @Return org.springframework.security.core.userdetails.UserDetails
     * @Throws
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userService.getUserByName(username);
        if(user==null){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return new AccountUser(user.getId(),user.getName(),user.getPassword(),getUserAuthority(user.getId()));
    }

    /**
     * @Name: getUserAuthority
     * @Params : [userId]:[java.lang.Long]
     * @Description : 获取用户权限
     * @Author : zpc20
     * @Date : 2023/11/2 8:39
     * @Return java.util.List<org.springframework.security.core.GrantedAuthority>
     * @Throws
     */
    public List<GrantedAuthority> getUserAuthority(Integer userId){

        String  authority = String.valueOf(userService.getBaseMapper().selectById(userId).getAuthorities());
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
